package com.siro.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.siro.auth.entity.SysDept;
import com.siro.auth.entity.SysUser;
import com.siro.auth.mapper.SysDeptMapper;
import com.siro.auth.mapper.SysUserMapper;
import com.siro.auth.service.ISysDeptService;
import com.siro.auth.base.common.domain.DeptTree;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author GH
 * @description 针对表【sys_dept(部门表)】的数据库操作Service实现
 * @createDate 2022-07-13 10:37:37
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询部门列表
     *
     * @param sysDept
     * @return
     */
    @Override
    public List<SysDept> getDeptList(SysDept sysDept) {

        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        //构造部门名称
        queryWrapper.like(!ObjectUtils.isEmpty(sysDept.getDeptName()), "dept_name", sysDept.getDeptName());
        //排序
        queryWrapper.orderByAsc("order_num");
        //查询部门列表
        List<SysDept> deptList = baseMapper.selectList(queryWrapper);
        //生成部门树
        List<SysDept> deptTreeList = DeptTree.makeDeptTree(deptList, 0L);

        return deptTreeList;
    }

    /**
     * 查询上级部门列表
     *
     * @return
     */
    @Override
    public List<SysDept> getParentDept() {
        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        //排序
        queryWrapper.orderByAsc("order_num");
        //查询部门列表
        List<SysDept> deptList = baseMapper.selectList(queryWrapper);
        //生成部门树
        List<SysDept> deptTreeList = DeptTree.makeDeptTree(deptList, 0L);

        return deptTreeList;
    }

    /**
     * 查询部门下是否存在子部门
     *
     * @param deptId
     * @return
     */
    @Override
    public boolean selectChildrenDept(Long deptId) {
        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", deptId);
        Integer count = baseMapper.selectCount(queryWrapper);
        //如果数量大于0，表示存在
        if (count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 查询部门下是否存在用户
     *
     * @param deptId
     * @return
     */
    @Override
    public boolean selectUserDept(Long deptId) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_id", deptId);
        Integer count = sysUserMapper.selectCount(queryWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }
}
